package com.apes.fa.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Title: FaAssetDepreciationService
 * @Description: 资产分类折旧
 * @author: ZhengZeXian
 * @create: 2021/12/22 15:02
 */
@Service("faAssetDepreciationService")
public class FaAssetDepreciationService extends DomainService {

    @Autowired
    private FaAssetDepreciationDao dao;
    @Autowired
    private FaAssetDepreciationRepository faAssetDepreciationRepository;

    @OutboxSubscriber(id = "event:faAsset.service.depreciation", name = "资产分类折旧")
    public void depreciation(OutboxPayloadWrapper wrapper){
        JSONObject input = JSON.parseObject(wrapper.getPayload());
        JSONArray array = dao.queryAsset(input);
        array.stream().forEach(a -> {
            JSONObject jsonObject = (JSONObject) a;

            String company_id = (String) jsonObject.get("COMPANY_ID");
            String cost_center_id = (String) jsonObject.get("COST_CENTER_ID");
            String fa_category_id = (String) jsonObject.get("FA_CATEGORY_ID");
            String yearMonth = (String) jsonObject.get("YEARMONTH");

            //获取当前年月和公司的所有卡片账数据
            List<FaAssetDepreciation> faAssetDepreciations = faAssetDepreciationRepository.
                    findByCompanyIdAndCostCenterIdAndFaCategoryId(company_id, cost_center_id, fa_category_id,yearMonth);

            if (faAssetDepreciations.size()!=0 && !faAssetDepreciations.isEmpty()){
                FaAssetDepreciation faAssetDepreciation = faAssetDepreciations.stream().findFirst().get();
                //原值增加
                faAssetDepreciation.setOriginalValueIncreased(jsonObject.getDoubleValue("BYZJ"));
                //原值减少
                faAssetDepreciation.setOriginalValueDecrease(jsonObject.getDoubleValue("BYJS"));
                //本月增加折旧
                faAssetDepreciation.setIncreaseDepreciation(jsonObject.getDoubleValue("ZJZJ"));
                //本月减少折旧
                faAssetDepreciation.setReduceDepreciation(jsonObject.getDoubleValue("JSZJ"));
                //累计折旧 改成本月已提折旧
                faAssetDepreciation.setAccumulatedDepreciation(jsonObject.getDoubleValue("YTZJ"));

                //写入完成
                faAssetDepreciation.setState("done");

                faAssetDepreciationRepository.saveAndFlush(faAssetDepreciation);
            }
        });
    }

}
